package com.limi.java8.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Java8 内置的四大核心函数式接口
 *
 * Consumer<T>:消费型接口
 *   void accept(T t);
 *
 * Supplier<T>:供给型接口
 *   T get();
 *
 * Function<T, R>:函数型接口
 *   R apply(T, t);
 *
 * Predicate<T>:断言型接口
 *   boolean test(T t);
 *
 * @author Limi Pan
 * @create 2018-09-25 21:38
 */
public class LambdaSample2 {

    //Consumer<T> 消费型接口：
    @Test
    public void test1(){
        happy(10000, (m) -> System.out.println("消费了"+m+"元。"));
    }

    public void happy(double money, Consumer<Double> consumer){
        consumer.accept(money);
    }

    //Supplier<T> 供给型接口
    @Test
    public void test2(){
        List<Integer> list = getNumList(10, () -> (int)(Math.random()*100));
        for (Integer i:list){
            System.out.println(i);
        }
    }

    //产生指定个数的整数，并放入结合中
    public List<Integer> getNumList(int num, Supplier<Integer> supplier){
        List<Integer> list = new ArrayList<>();
        for (int i=0;i<num;i++){
            Integer integer = supplier.get();
            list.add(integer);
        }
        return list;
    }

    //Function<T, R> 函数式接口
    @Test
    public void test3(){
        String newStr = strHandler("  \t\t\t 好好学习，天天向上。  ", (str) -> str.trim());
        System.out.println(newStr);
    }

    //用于处理字符串
    public String strHandler(String str, Function<String, String> fun){
        return fun.apply(str);
    }

    //Predicate<T> 断言型接口
    @Test
    public void test4(){
        List<String> list = Arrays.asList("Hello", "Limi", "World", "Mark");
        List<String> list1 = filterStr(list, (s) -> s.length()>4);
        for (String str:list1){
            System.out.println(str);
        }
    }

    //将满足条件的字符串，放入集合中
    public List<String> filterStr(List<String> list, Predicate<String> pre){
        List<String> strList = new ArrayList<>();
        for (String str : list){
            if (pre.test(str)){
                strList.add(str);
            }
        }
        return strList;
    }
}
